# coding: utf-8
from django.conf import settings
from django import forms
from django.core.mail import EmailMessage, send_mail
from django.template.context import Context
from django.template.loader import render_to_string

from models import FeedbackFormManager


class FeedbackFormPrototype(object):
    feedback_form = True

    title = u'Сообщение с сайта'
    template = 'feedback/feedback_email.txt'
    
    def get_recipients(self):
        if not hasattr(self, 'slug'):
            raise NotImplementedError('Slug does not exist.')

        try:
            form_manager = FeedbackFormManager.objects.get(slug=self.slug)
            return form_manager.email.all().values_list('email', flat=True)
        except FeedbackFormManager.DoesNotExist:
            return list()

    @property
    def subject(self):
        return '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, self.title)
    
    def update_context(self, **kwargs):
        self.extra_context = kwargs
        return self
        
    def get_context(self):
        context = dict()

        if hasattr(self, 'cleaned_data'):
            context.update(self.cleaned_data)

        if hasattr(self, 'extra_context'):
            context.update(self.extra_context)

        return context


class MailFormPrototype(FeedbackFormPrototype):
    def save(self):
        context = self.get_context()
        send_mail(self.subject, 
                  render_to_string(self.template, Context(context)), 
                  settings.DEFAULT_FROM_EMAIL, 
                  self.get_recipients())


class BaseFeedbackForm(forms.Form, MailFormPrototype):
    pass


class ModelFeedbackForm(forms.ModelForm, FeedbackFormPrototype):
    def save(self, commit=True):
        context = self.get_context()
        obj = super(ModelFeedbackForm, self).save(commit)
        context.update({'object': obj})
        send_mail(self.subject, 
                  render_to_string(self.template, Context(context)), 
                  settings.DEFAULT_FROM_EMAIL, 
                  self.get_recipients())
        return obj
        



class FeedbackForm(BaseFeedbackForm):
    slug = 'feedback'
    title = u'Сообщение с сайта'

    name = forms.CharField(label=u'Ваше имя', max_length=80, widget=forms.TextInput(attrs={'placeholder': u'Представьтесь'}))
    email = forms.EmailField(label=u'Ваш e-mail', widget=forms.TextInput(attrs={'placeholder': u'Электронная почта для ответа'}))
    message = forms.CharField(label=u'Сообщение', widget=forms.Textarea)

    confirm = forms.CharField(label=u"Подтвердить", required=False)
    def clean_confirm(self):
        context = self.cleaned_data
        if context['confirm']:
            raise forms.ValidationError(u'Не заполняйте это поле.')
        return None
